<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>
      
      <div class="profile-content">
        <div class="user-avatar-section">
          <div class="avatar-container" @click="triggerAvatarInput">
            <el-avatar :size="80" :src="userInfo.avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="avatar-overlay">
              <el-icon><Camera /></el-icon>
              <span>更换头像</span>
            </div>
          </div>
          <input
            ref="avatarInput"
            type="file"
            accept="image/*"
            style="display: none;"
            @change="handleAvatarFileChange"
          />
          <div class="avatar-actions">
            <el-button type="primary" size="small" @click="triggerAvatarInput" :loading="uploadingAvatar">
              {{ uploadingAvatar ? '上传中...' : '更换头像' }}
            </el-button>
            <el-button v-if="userInfo.avatar" size="small" type="danger" @click="removeAvatar">
              移除头像
            </el-button>
          </div>
        </div>
        
        <div class="user-info-section">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="用户名">
              {{ userInfo.username }}
            </el-descriptions-item>
            <el-descriptions-item label="昵称">
              {{ userInfo.nickname || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ userInfo.email }}
            </el-descriptions-item>
            <el-descriptions-item label="用户角色">
              {{ getUserRoleText(userInfo.role) }}
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ formatDate(userInfo.createTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="action-section">
          <el-button type="primary" @click="handleEditProfile">
            编辑资料
          </el-button>
          <el-button @click="handleChangePassword">
            修改密码
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 编辑资料对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑资料" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProfile" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePasswordSubmit" :loading="changingPassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 定义组件名称用于 keep-alive
defineOptions({
  name: 'Profile'
})

import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Camera } from '@element-plus/icons-vue'
import { useAuth } from '@/composables/useAuth'
import { uploadApi } from '@/services/uploadApi'

// 使用认证组合式函数
const { user, updateProfile } = useAuth()

// 响应式数据
const userInfo = computed(() => user.value || {})
const showEditDialog = ref(false)
const showPasswordDialog = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const uploadingAvatar = ref(false)
const editFormRef = ref()
const passwordFormRef = ref()
const avatarInput = ref()

// 编辑表单
const editForm = reactive({
  nickname: '',
  email: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const editRules = {
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法 - 用户信息现在通过computed属性自动获取，无需手动加载

const getUserRoleText = (role) => {
  const roleMap = {
    'admin': '系统管理员',
    'user': '普通用户',
    'vip': 'VIP用户',
    'premium': '高级用户'
  }
  return roleMap[role] || '普通用户'
}

const formatDate = (dateStr) => {
  if (!dateStr) return '暂无'
  try {
    return new Date(dateStr).toLocaleString('zh-CN')
  } catch (error) {
    return '暂无'
  }
}

// 头像上传相关方法
const triggerAvatarInput = () => {
  avatarInput.value?.click()
}

const handleAvatarFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件!')
    return
  }

  // 验证文件大小（5MB）
  if (file.size / 1024 / 1024 > 5) {
    ElMessage.error('图片大小不能超过 5MB!')
    return
  }

  uploadingAvatar.value = true

  try {
    // 上传头像到OSS
    const uploadResponse = await uploadApi.uploadAvatar(file)

    // 更新用户头像到认证store（会自动调用后端API）
    await updateProfile({
      avatar: uploadResponse.url
    })

    ElMessage.success('头像更新成功!')

    // 清空input的值
    event.target.value = ''
  } catch (error) {
    console.error('头像更新失败:', error)
    ElMessage.error('头像更新失败: ' + (error.message || '未知错误'))
  } finally {
    uploadingAvatar.value = false
  }
}

const removeAvatar = async () => {
  try {
    // 移除用户头像（会自动调用后端API）
    await updateProfile({
      avatar: ''
    })

    ElMessage.success('头像已移除')
  } catch (error) {
    console.error('移除头像失败:', error)
    ElMessage.error('移除头像失败: ' + (error.message || '未知错误'))
  }
}

const handleEditProfile = () => {
  editForm.nickname = userInfo.value.nickname || ''
  editForm.email = userInfo.value.email || ''
  showEditDialog.value = true
}

const handleChangePassword = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  showPasswordDialog.value = true
}

const handleSaveProfile = async () => {
  try {
    await editFormRef.value.validate()
    saving.value = true

    // 更新用户信息（会自动调用后端API）
    await updateProfile({
      nickname: editForm.nickname,
      email: editForm.email
    })

    ElMessage.success('资料更新成功')
    showEditDialog.value = false

  } catch (error) {
    console.error('更新资料失败:', error)
    ElMessage.error('更新资料失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

const handleChangePasswordSubmit = async () => {
  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true
    
    // 这里应该调用修改密码的API
    // await userApi.changePassword(passwordForm)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false
    
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    changingPassword.value = false
  }
}

// 生命周期 - 用户信息现在通过computed属性自动获取
onMounted(() => {
  // 用户信息已通过认证store自动管理，无需手动加载
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.user-avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 20px;
  border-radius: 8px;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  font-size: 12px;
  gap: 4px;
}

.avatar-overlay .el-icon {
  font-size: 20px;
}

.avatar-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.user-info-section {
  width: 100%;
}

.action-section {
  display: flex;
  gap: 15px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  
  margin-bottom: 20px;
}

:deep(.el-descriptions__body .el-descriptions__table) {
  border-radius: 6px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  
}
</style>
